/*
 * @lc app=leetcode.cn id=501 lang=csharp
 *
 * [501] 二叉搜索树中的众数
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public int[] FindMode(TreeNode root) {
        List<int> result = new List<int>();
        int maxCount = 0;
        int currentCount = 0;
        int? previousValue = null;
        void InOrder(TreeNode node)
        {
            if (node == null)
            {
                return;
            }
            InOrder(node.left);
            if (previousValue == null || node.val != previousValue)
            {
                currentCount = 1;
            }
            else
            {
                currentCount++;
            }
            if (currentCount > maxCount)
            {
                result.Clear();
                result.Add(node.val);
                maxCount = currentCount;
            }
            else if (currentCount == maxCount)
            {
                result.Add(node.val);
            }
            previousValue = node.val;
            InOrder(node.right);
        }
        InOrder(root);
        return result.ToArray();
    
    }
}
// @lc code=end

